package backed.controller;

import backed.service.GarbageSortService;
import backed.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 垃圾分类控制器
 */
@io.swagger.v3.oas.annotations.tags.Tag(name = "垃圾分类", description = "垃圾分类识别和历史查询接口")
@RestController
@CrossOrigin
@RequestMapping("/api/garbage")
public class GarbageSortController {
    
    @Autowired
    private GarbageSortService garbageSortService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 垃圾分类识别接口
     */
    @Operation(summary = "垃圾分类识别", description = "上传图片进行垃圾分类识别，返回物品名称、分类和建议。注意：必须使用 multipart/form-data 格式上传文件")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "识别成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误或文件格式不支持"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "识别失败")
    })
    @PostMapping(value = "/classify", consumes = "multipart/form-data")
    public Object classify(
            @Parameter(description = "用户ID", required = true, example = "1")
            @RequestParam("userId") Long userId,
            @Parameter(description = "图片文件（支持jpg、jpeg、png、gif、webp格式，最大10MB）", required = true, 
                       schema = @Schema(type = "string", format = "binary"))
            @RequestPart(value = "image", required = true) MultipartFile imageFile,
            @Parameter(description = "用户问题（可选）", required = false, example = "这是什么垃圾")
            @RequestParam(value = "question", required = false) String question) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 参数校验
            if (userId == null) {
                result.put("success", false);
                result.put("message", "用户ID不能为空");
                return result;
            }
            
            if (imageFile == null || imageFile.isEmpty()) {
                result.put("success", false);
                result.put("message", "图片文件不能为空");
                return result;
            }
            
            // 2. 验证用户是否存在
            if (userService.getUserInfo(userId) == null) {
                result.put("success", false);
                result.put("message", "用户不存在，用户ID: " + userId);
                return new org.springframework.http.ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }
            
            // 3. 文件类型校验
            String originalFilename = imageFile.getOriginalFilename();
            if (originalFilename == null || 
                (!originalFilename.toLowerCase().endsWith(".jpg") &&
                 !originalFilename.toLowerCase().endsWith(".jpeg") &&
                 !originalFilename.toLowerCase().endsWith(".png") &&
                 !originalFilename.toLowerCase().endsWith(".gif") &&
                 !originalFilename.toLowerCase().endsWith(".webp"))) {
                result.put("success", false);
                result.put("message", "不支持的图片格式，仅支持jpg、jpeg、png、gif、webp格式");
                return result;
            }
            
            // 4. 调用服务进行垃圾分类
            return garbageSortService.classifyGarbage(userId, imageFile, question);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "垃圾分类识别失败: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 获取垃圾分类历史记录
     */
    @Operation(summary = "获取垃圾分类历史", description = "获取指定用户的垃圾分类历史记录")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @GetMapping("/history")
    public Object getHistory(
            @Parameter(description = "用户ID", required = true, example = "1")
            @RequestParam("userId") Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 参数校验
            if (userId == null) {
                result.put("success", false);
                result.put("message", "用户ID不能为空");
                return result;
            }
            
            // 2. 验证用户是否存在
            if (userService.getUserInfo(userId) == null) {
                result.put("success", false);
                result.put("message", "用户不存在，用户ID: " + userId);
                return new org.springframework.http.ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }
            
            // 3. 获取历史记录
            List<Map<String, Object>> history = garbageSortService.getHistory(userId);
            
            result.put("success", true);
            result.put("data", history);
            
            return result;
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取历史记录失败: " + e.getMessage());
            return result;
        }
    }
}

